package com.enjoy.activemq.api;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * @Auther guwenbo
 * @Date 2018/11/23
 */
public class ConsumerAsyn {

    private static final String USER_NAME =
//            "admin";
            ActiveMQConnection.DEFAULT_USER;

    private static final String PASSWORD =
//            "admin";
            ActiveMQConnection.DEFAULT_PASSWORD;

    private static final String BROKE_URL =
            "tcp://47.99.197.150:61616";
//            ActiveMQConnection.DEFAULT_BROKER_URL;

    public static void startConsumer(){
        ConnectionFactory factory;
        Connection connection = null;
        Session session;
        Destination destination;
        MessageConsumer messageConsumer;


        factory = new ActiveMQConnectionFactory(USER_NAME,PASSWORD,BROKE_URL);

        try {
            connection = factory.createConnection();
            connection.start();
            session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
//            destination = session.createTopic("guwenboMQ");
            destination = session.createQueue("guwenboMQ");
            messageConsumer = session.createConsumer(destination);
            messageConsumer.setMessageListener(new MessageListener() {
                public void onMessage(Message message) {
                    try {
                        System.out.println(((TextMessage)message).getText());
                    } catch (JMSException e) {
                        e.printStackTrace();
                    }
                }
            });


        } catch (JMSException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        }


    }

    public static void main(String[] args) {
        startConsumer();
    }
}
